package com.frame.jfinal.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import com.frame.ar.util.Coder;
import com.frame.config.SystemParamsConfig;
import com.frame.config.SystemParamsConfig.ManagerParam;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.system.model.User;

/*******************************************
 * 作用描述：根请求服务层
 *******************************************
 * @author LRC
 * @createDate 2015-9-11
 * @version v1.0 
 * @updateRecord 格式：时间，作者，修改说明
 *******************************************
 * 
 */
public class RootService {

	/**
	 * @updateTeim 2015年5月22日上午12:24:41
	 * @description 执行登录验证 
	 * @return 
	 */
	public static User validateLogin(String userCode, String loginPwd) {
		//查询用户信息
		//User u = User.dao.findFirst("select * from sys_base_user where userCode=? and status not in(-1,0) ", usercode);
		User u = User.dao.findByUserCode(userCode);
		if(u==null)return null;
		//判断用户状态
		int status = u.getInt("status");
		if(status==2){
			//锁定状态
			User.dao.lockUser(userCode);
			return u;
		}
		//判断是否处于-1 注销， 0 未激活状态
		if(status==-1 || status == 0){
			return null;
		}
		//获取用户密码解码字符串
		String _dePwd = Coder.base64Decode(loginPwd);
		String dePwd = _dePwd.substring(userCode.length());
		//获取密码摘要
		String enPwd = Coder._encoder(dePwd, userCode);
		//判断密码是否正确
		String correctPwd = u.getStr("password");
		if(!correctPwd.equals(enPwd)){
			//验证密码出错
			//获取登录失败此时
			int loginFailedNum = u.getInt("loginFailedNum");
			//登录失败次数加一
			loginFailedNum++;
			//判断是否超过锁定次数
			ManagerParam p = SystemParamsConfig.getInstance().getManagerParam();
			if(loginFailedNum>p.loginFailedNum){
				//将账号锁定
				u.set("status", 2).set("lockedTime", new Date());
				//加入被锁池
				User.dao.lockUser(userCode);
			}else{
				//更新失败次数
				u.set("loginFailedNum", loginFailedNum);
			}
			u.update();
		}else{
			//登录成功,更新状态及最后一次登录时间
			u.set("online", 1).set("lastLoginTime", new Date());
			//登录失败次数置0
			u.set("loginFailedNum", 0);
			//执行保存更新
			u.update();
		}
		return u;
	}

	/**
	 * @updateTeim 2015年5月22日上午12:26:45
	 * @description 锁定用户
	 * @param usercode
	 */
	public static void lockUser(String usercode) {
		
	}

	/**
	 * @updateTeim 2015年5月23日上午10:56:35
	 * @description 用户登出操作
	 * @param u
	 */
	public static void userLogout(User u) {
		/*
		 * 1、判断用户是否为空
		 * 2、设置用户不在线
		 */
		if(u!=null&&u.getStr("userCode")!=null){
			User _u = User.dao.findByUserCode(u.getStr("userCode"));
			if(_u!=null){
				_u.set("online", 0).update();
			}
		}
	}

	/**
	 * @updateTeim 2015年5月24日下午2:54:40
	 * @description 提交球场管理注册申请
	 * @param c
	 */
	public static JSONObject groundMgrRegister(Controller c) {
		JSONObject data = new JSONObject();
		String userCode = c.getPara("userCode");
		User u = User.dao.findFirst("select * from sys_base_user where userCode=?", userCode);
		if(u!=null){
			data.put("msg", "注册的登录名已经存在");
			data.put("result", false);
			return data;
		}
		//获取用户信息
		u = new User();
		u.set("userCode", userCode);
		String password = Coder.base64Decode(c.getPara("password"));
		u.set("password", Coder._encoder(password, userCode));
		u.set("email", c.getPara("email"));
		u.set("userName", c.getPara("userName"));
		u.set("telephone", c.getPara("telephone"));
		u.set("address", c.getPara("address"));
		u.set("userType", "groundsman");//用户类型为球场管理员
		u.set("status", 0);//默认状态未激活
		boolean result = u.set("insertTime", new Date()).save();
		if(result){
			data.put("msg", "注册申请提交成功，等待审核！");
		}else{
			data.put("msg", "注册申请提交失败，请联系管理员处理！");
		}
		data.put("result", result);
		return data;
	}

	/**
	 * @updateTeim 2015年6月25日下午9:24:38
	 * @description 获取用户菜单权限 
	 * @param u
	 */
	public static List<Record> getUserMenu(User u) {
		if(u==null)return null;
		List<Record> nav = new ArrayList<Record>();
		Map<Integer,Record> tempMenus = new HashMap<Integer,Record>();
		String userCode = u.getStr("userCode");
		if("superAdmin".equals(userCode)){
			//超级管理员拥有所有权限
			List<Record> menus = Db.find("select distinct m.id,m.name,m.url,m.parentId,m.icon,menuLevel,idPath from sys_base_menu m "
					+ "where m.menuLevel in(1,2) order by menuLevel,orderSn");
			for(Record m : menus){
				int id = m.getInt("id");
				int level = m.getInt("menuLevel");
				if(level==1){
					//添加子列表
					List<Record> subMenu = new ArrayList<Record>();
					m.set("subMenu", subMenu);
				}
				tempMenus.put(id, m);
			}
			//菜单三层结构
			for(Record m : menus){
				int level = m.getInt("menuLevel");
				switch(level){
				case 1:
					nav.add(m);
					continue;
				case 2:
					//查询第二层的子菜单
					int parentId = m.getInt("parentId");
					Record parent = tempMenus.get(parentId);
					List<Record> subMenu = parent.get("subMenu");
					subMenu.add(m);
					//填充子菜单
					String idPath = m.getStr("idPath");
					List<Record> subMenus = Db.find("select distinct m.id,m.name,m.url,m.parentId,m.icon,menuLevel from sys_base_menu m "
							+ "where m.menuLevel not in(0,1,2) and idPath like ? order by menuLevel,orderSn",idPath+"-%");
					m.set("subMenu", subMenus);
					break;
					/**
				case 3:
					int parentId = m.getInt("parentId");
					Record parent = tempMenus.get(parentId);
					List<Record> subMenu = parent.get("subMenu");
					subMenu.add(m);
					break;
					**/
				}
			}
		}else{
			Object uid = u.getInt("id");
			//查询用户拥有的菜单信息
			List<Record> menus = Db.find("select distinct m.id,m.name,m.url,m.parentId,m.icon,menuLevel,idPath from sys_base_menu m left join sys_base_usermenu um on um.menuId=m.id "
					+ " where um.userId=? and m.menuLevel in(1,2) order by menuLevel,orderSn",uid);
			for(Record m : menus){
				int id = m.getInt("id");
				int level = m.getInt("menuLevel");
				if(level==1){
					//添加子列表
					List<Record> subMenu = new ArrayList<Record>();
					m.set("subMenu", subMenu);
				}
				tempMenus.put(id, m);
			}
			//菜单三层结构
			for(Record m : menus){
				int level = m.getInt("menuLevel");
				switch(level){
				case 1:
					nav.add(m);
					continue;
				case 2:
					//查询第二层的子菜单
					int parentId = m.getInt("parentId");
					Record parent = tempMenus.get(parentId);
					List<Record> subMenu = parent.get("subMenu");
					subMenu.add(m);
					//填充子菜单
					String idPath = m.getStr("idPath");
					List<Record> subMenus = Db.find("select distinct m.id,m.name,m.url,m.parentId,m.icon,menuLevel from sys_base_menu m left join sys_base_usermenu um on um.menuId=m.id "
							+ "where um.userId=? and m.menuLevel not in(0,1,2) and idPath like ? order by menuLevel,orderSn",uid,idPath+"-%");
					m.set("subMenu", subMenus);
					break;
					/**
				case 3:
					int parentId = m.getInt("parentId");
					Record parent = tempMenus.get(parentId);
					List<Record> subMenu = parent.get("subMenu");
					subMenu.add(m);
					break;
					**/
				}
			}
		}
		
		return nav;
		
	}

}
